package com.ai.alibaba.bailian;

import com.ai.util.FrameHelper;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import com.alibaba.cloud.ai.dashscope.chat.MessageFormat;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.Media;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 *
 * 解析视频的含义
 * @author houwenpeng
 */
@RestController
@RequestMapping("/ai/video")
public class VideoToText {
    @Resource
    private ChatModel chatModel;

    @PostMapping("/video")
    public String video(@Validated MultipartFile file, @Validated String message) {
        String directoryPath =  "D:\\project\\AI\\src\\main\\resources\\output";
        cleanDirectory(new File(directoryPath));
        // 1、视频图片
        List<Media> mediaList = FrameHelper.load(file);
        UserMessage userMessage = new UserMessage(message, mediaList);
        userMessage.getMetadata().put(DashScopeChatModel.MESSAGE_FORMAT, MessageFormat.VIDEO);
        // 2、发送请求
        ChatResponse chatResponse = chatModel.call(new Prompt(userMessage, DashScopeChatOptions.builder()
                .withModel("qwen-vl-max-latest")
                .withMultiModel(true).build()));
        return chatResponse.getResult().getOutput().getContent();
    }

    /**
     * 清空目录
     * @param directory
     */
    private static void cleanDirectory(File directory) {
        if (directory.exists() && directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        // 递归清空子目录
                        cleanDirectory(file);
                    }
                    // 删除文件或空目录
                    if (file.delete()) {
                        System.out.println("已删除: " + file.getAbsolutePath());
                    } else {
                        System.err.println("删除失败: " + file.getAbsolutePath());
                    }
                }
            }
        }
    }
}